package com.quotemanager.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectionFactory {
	
	public final static String QUOTE_MANAGER_DS_NAME = "java:/comp/env/jdbc/qm";

	private static Map dsMap = new HashMap();

	private static ConnectionFactory instance = null;

	static {
		try {
			javax.naming.InitialContext ctx = new javax.naming.InitialContext();
			DataSource dataSource = (DataSource) ctx.lookup(QUOTE_MANAGER_DS_NAME);
			dsMap.put(QUOTE_MANAGER_DS_NAME, dataSource);
		//	DataSource dataSourceXA = (DataSource) ctx.lookup(MEDIADSXA);
		//	dsMap.put(MEDIADSXA, dataSourceXA);

		} catch (NamingException e) {
			System.out.println("Error retrieving data source:" + e);
			throw new RuntimeException(e);
		}

	}

	public static ConnectionFactory getInstance() {
		if (instance == null) {
			instance = new ConnectionFactory();
		}
		return instance;
	}
	
	public static Connection getConnection()throws SQLException {
		return getConnection(QUOTE_MANAGER_DS_NAME);
	}

	public static Connection getConnection(String ds)throws SQLException {
			DataSource dataSource = (DataSource) dsMap.get(ds);
			return dataSource.getConnection();
	}
	
	public static void closeAll(Connection con, Statement st, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
		} catch (SQLException e) {
			System.out.println("Can not close Statement or ResultSet");
		} finally {
			try {
				if (con != null) {
					con.close();
				}
			} catch (SQLException e) {
				System.out.println("Can not close Connection");
			}
		}
	}
}
